<?php

namespace App\Http\Controllers\Api\V1\Mes;

use App\Constants\BaseConstant;
use App\Helpers\ResponseHelper;
use App\Helpers\V1\AuthMenuHelper;
use App\Http\Controllers\Controller;
use App\Models\Mes\AuthMenu;
use App\Models\Mes\AuthRole;
use App\Models\Mes\AuthRoleMenu;
use App\Models\Mes\AuthUser;
use App\Models\Mes\AuthUserRole;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class AuthRoleController extends Controller
{
    /*
     * 角色列表
     */
    public function list(Request $request): JsonResponse
    {
        $list = AuthRole::query()
            ->with(["role_menus"])
            ->orderBy("id", "desc")
            ->get()
            ->map(function ($item) {
                $item->menus = $item->role_menus->pluck("menu_id");
                return $item->only(["id", "name", "menus"]);
            });
        $result = AuthMenu::query()
            ->orderBy("sort", "asc")
            ->get();
        $l = AuthMenuHelper::getTree($result);
        $menus = [[
            "id" => 0,
            "name" => "全部",
            "children" => $l
        ]];
        $return = compact("list", "menus");
        return ResponseHelper::json(0, "success", $return);
    }

    /*
     * 添加角色
     */
    public function create(Request $request): JsonResponse
    {
        try {
            $data = $request->all();
            $class = AuthRole::class;
            $validator = Validator::make($data, [
                "name" => "required|unique:{$class},name"
            ], [
                "name.required" => "请填写角色名称",
                "name.unique" => "该角色已存在，请勿重复添加"
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }
            AuthRole::query()->create($request->only(["name"]));
        } catch (\Exception $e) {
            return ResponseHelper::json($e->getCode() ?: 20001, $e->getMessage());
        }
        return ResponseHelper::json(0, "添加成功");
    }

    /*
     * 修改
     */
    public function modify(Request $request) :JsonResponse
    {
        try {
            $data = $request->all();
            $role = AuthRole::query()->find($request->input("id"));
            if (!$role) {
                throw new \Exception("角色异常，请刷新页面重试");
            }
            $table = $role->getTable();
            $validator = Validator::make($data, [
                "name" => [
                    "required",
                    Rule::unique($table)->ignore($role)
                ],
                "menus" => "nullable|array"
            ], [
                "name.required" => "请填写角色名称",
                "name.unique" => "该角色已存在，请勿重复添加",
                "menus.*" => "请选择角色权限"
            ]);
            if ($validator->fails()) {
                throw new \Exception($validator->errors()->first());
            }
            DB::beginTransaction();
            $role->name = $request->input("name");
            $role->save();
            // 写入角色功能表
            AuthRoleMenu::query()->where("role_id", $role->id)->delete();
            if ($request->input("menus")) {
                foreach ($request->input("menus") as $menu) {
                    AuthRoleMenu::query()->create([
                        "role_id" => $role->id,
                        "menu_id" => $menu
                    ]);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            return ResponseHelper::json($e->getCode() ?: 20001, $e->getMessage());
        }
        return ResponseHelper::json(0, "操作成功");
    }

    /*
     * 删除
     */
    public function delete(Request $request) : JsonResponse
    {
        try {
            $data = $request->all();
            $role = AuthRole::query()->find($request->input("id"));
            if (!$role) {
                throw new \Exception("角色异常，请刷新页面重试");
            }
            // 检测该角色下是否存在用户
            $user = AuthUserRole::query()->where("role_id", $role->id)->exists();
            if ($user) {
                throw new \Exception("该角色下存在用户，请先取消用户权限");
            }
            DB::beginTransaction();
            AuthRoleMenu::query()->where("role_id", $role->id)->delete();
            $role->delete();
            DB::commit();
        } catch (\Exception $e) {
            return ResponseHelper::json($e->getCode() ?: 20001, $e->getMessage());
        }
        return ResponseHelper::json(0, "操作成功");
    }

    /*
     * 用户列表
     */
    public function users(Request $request)
    {
        $role_id = $request->input("role_id");
        $result = AuthUser::query()
            ->whereHas("auth_roles", function ($query) use ($role_id) {
                return $query->where("role_id", $role_id);
            })
            ->paginate($request->input("size"));

        $list = $result->getCollection()->map(function ($item) {
            $roles = $item->auth_roles->pluck("role_id");
            return [
                "name" => $item->name,
                "code" => $item->code,
                "status" => (string)$item->status,
                "status_formatted" => BaseConstant::$statuses[$item->status],
                "roles" => $roles
            ];
        });
        $max_pages = $result->lastPage();
        $total = $result->total();
        $return = compact("list", "max_pages", "total");
        return ResponseHelper::json(0, "success", $return);
    }
}
